{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    " 100 numpy exercises\n",
    "\n",
    "This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow and in the numpy documentation. The goal of this collection is to offer a quick reference for both old and new users but also to provide a set of exercises for those who teach.\n",
    "\n",
    "\n",
    "If you find an error or think you've a better way to solve some of them, feel free to open an issue at <https://github.com/rougier/numpy-100>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1. Import the numpy package under the name `np` (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. Print the numpy version and the configuration (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.14.2\n",
      "mkl_info:\n",
      "    libraries = ['mkl_rt']\n",
      "    library_dirs = ['C:/ProgramData/Anaconda3\\\\Library\\\\lib']\n",
      "    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]\n",
      "    include_dirs = ['C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl', 'C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl\\\\include', 'C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl\\\\lib', 'C:/ProgramData/Anaconda3\\\\Library\\\\include']\n",
      "blas_mkl_info:\n",
      "    libraries = ['mkl_rt']\n",
      "    library_dirs = ['C:/ProgramData/Anaconda3\\\\Library\\\\lib']\n",
      "    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]\n",
      "    include_dirs = ['C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl', 'C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl\\\\include', 'C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl\\\\lib', 'C:/ProgramData/Anaconda3\\\\Library\\\\include']\n",
      "blas_opt_info:\n",
      "    libraries = ['mkl_rt']\n",
      "    library_dirs = ['C:/ProgramData/Anaconda3\\\\Library\\\\lib']\n",
      "    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]\n",
      "    include_dirs = ['C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl', 'C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl\\\\include', 'C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl\\\\lib', 'C:/ProgramData/Anaconda3\\\\Library\\\\include']\n",
      "lapack_mkl_info:\n",
      "    libraries = ['mkl_rt']\n",
      "    library_dirs = ['C:/ProgramData/Anaconda3\\\\Library\\\\lib']\n",
      "    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]\n",
      "    include_dirs = ['C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl', 'C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl\\\\include', 'C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl\\\\lib', 'C:/ProgramData/Anaconda3\\\\Library\\\\include']\n",
      "lapack_opt_info:\n",
      "    libraries = ['mkl_rt']\n",
      "    library_dirs = ['C:/ProgramData/Anaconda3\\\\Library\\\\lib']\n",
      "    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]\n",
      "    include_dirs = ['C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl', 'C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl\\\\include', 'C:\\\\Program Files (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2016.4.246\\\\windows\\\\mkl\\\\lib', 'C:/ProgramData/Anaconda3\\\\Library\\\\include']\n"
     ]
    }
   ],
   "source": [
    "print(np.__version__)\n",
    "np.show_config()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. Create a null vector of size 10 (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n"
     ]
    }
   ],
   "source": [
    "Z = np.zeros(10)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4.  How to find the memory size of any array (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "800 bytes\n"
     ]
    }
   ],
   "source": [
    "Z = np.zeros((10,10))\n",
    "print(\"%d bytes\" % (Z.size * Z.itemsize))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 5.  How to get the documentation of the numpy add function from the command line? (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "ERROR:root:File `'`python.py'` not found.\n"
     ]
    }
   ],
   "source": [
    "%run `python -c \"import numpy; numpy.info(numpy.add)\"`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 6.  Create a null vector of size 10 but the fifth value which is 1 (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [
    {
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-1-3ad7d656eb82>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mZ\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mzeros\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      2\u001b[0m \u001b[0mZ\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mZ\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mNameError\u001b[0m: name 'np' is not defined"
     ],
     "ename": "NameError",
     "evalue": "name 'np' is not defined",
     "output_type": "error"
    }
   ],
   "source": [
    "Z = np.zeros(10)\n",
    "Z[4] = 1\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 7.  Create a vector with values ranging from 10 to 49 (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33\n",
      " 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]\n"
     ]
    }
   ],
   "source": [
    "Z = np.arange(10,50)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 8.  Reverse a vector (first element becomes last) (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26\n",
      " 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2\n",
      "  1  0]\n"
     ]
    }
   ],
   "source": [
    "Z = np.arange(50)\n",
    "Z = Z[::-1]\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 9.  Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 1 2]\n",
      " [3 4 5]\n",
      " [6 7 8]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.arange(9).reshape(3,3)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 10. Find indices of non-zero elements from \\[1,2,0,0,4,0\\] (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(array([0, 1, 4], dtype=int64),)\n"
     ]
    }
   ],
   "source": [
    "nz = np.nonzero([1,2,0,0,4,0])\n",
    "print(nz)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 11. Create a 3x3 identity matrix (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1. 0. 0.]\n",
      " [0. 1. 0.]\n",
      " [0. 0. 1.]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.eye(3)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 12. Create a 3x3x3 array with random values (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[0.38623687 0.72860689 0.11861256]\n",
      "  [0.87583184 0.75984112 0.92027858]\n",
      "  [0.15569262 0.24601167 0.40514924]]\n",
      "\n",
      " [[0.23179978 0.41058658 0.97117928]\n",
      "  [0.76418077 0.5534301  0.52208481]\n",
      "  [0.6620278  0.92392492 0.58433957]]\n",
      "\n",
      " [[0.14777566 0.83096875 0.20888782]\n",
      "  [0.94630753 0.14862539 0.88969933]\n",
      "  [0.10930963 0.13027745 0.41575222]]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.random.random((3,3,3))\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.004334784341918696 0.9914238367397242\n"
     ]
    }
   ],
   "source": [
    "Z = np.random.random((10,10))\n",
    "Zmin, Zmax = Z.min(), Z.max()\n",
    "print(Zmin, Zmax)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 14. Create a random vector of size 30 and find the mean value (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.5720815414833132\n"
     ]
    }
   ],
   "source": [
    "Z = np.random.random(30)\n",
    "m = Z.mean()\n",
    "print(m)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]\n",
      " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n",
      " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n",
      " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n",
      " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n",
      " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n",
      " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n",
      " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n",
      " [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n",
      " [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.ones((10,10))\n",
    "Z[1:-1,1:-1] = 0\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 16. How to add a border (filled with 0's) around an existing array? (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 1. 1. 1. 1. 1. 0.]\n",
      " [0. 1. 1. 1. 1. 1. 0.]\n",
      " [0. 1. 1. 1. 1. 1. 0.]\n",
      " [0. 1. 1. 1. 1. 1. 0.]\n",
      " [0. 1. 1. 1. 1. 1. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0.]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.ones((5,5))\n",
    "Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 17. What is the result of the following expression? (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "nan\n",
      "False\n",
      "False\n",
      "nan\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "print(0 * np.nan)\n",
    "print(np.nan == np.nan)\n",
    "print(np.inf > np.nan)\n",
    "print(np.nan - np.nan)\n",
    "print(np.nan in set([np.nan]))\n",
    "print(0.3 == 3 * 0.1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 0 0 0 0]\n",
      " [1 0 0 0 0]\n",
      " [0 2 0 0 0]\n",
      " [0 0 3 0 0]\n",
      " [0 0 0 4 0]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.diag(1+np.arange(4),k=-1)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 1 0 1 0 1 0 1]\n",
      " [1 0 1 0 1 0 1 0]\n",
      " [0 1 0 1 0 1 0 1]\n",
      " [1 0 1 0 1 0 1 0]\n",
      " [0 1 0 1 0 1 0 1]\n",
      " [1 0 1 0 1 0 1 0]\n",
      " [0 1 0 1 0 1 0 1]\n",
      " [1 0 1 0 1 0 1 0]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.zeros((8,8),dtype=int)\n",
    "Z[1::2,::2] = 1\n",
    "Z[::2,1::2] = 1\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 5, 4)\n"
     ]
    }
   ],
   "source": [
    "print(np.unravel_index(100,(6,7,8)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 1 0 1 0 1 0 1]\n",
      " [1 0 1 0 1 0 1 0]\n",
      " [0 1 0 1 0 1 0 1]\n",
      " [1 0 1 0 1 0 1 0]\n",
      " [0 1 0 1 0 1 0 1]\n",
      " [1 0 1 0 1 0 1 0]\n",
      " [0 1 0 1 0 1 0 1]\n",
      " [1 0 1 0 1 0 1 0]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.tile( np.array([[0,1],[1,0]]), (4,4))\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 22. Normalize a 5x5 random matrix (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.60460987  1.57268218 -0.89575026  0.39473056 -1.03035535]\n",
      " [ 0.48811681  0.27544473 -0.44867393  0.29267064 -0.68241891]\n",
      " [-0.3952934  -1.05912252 -1.38505776  0.35666151  0.27154967]\n",
      " [-1.11291754 -1.55657621  1.41843066  1.9689818   0.90553902]\n",
      " [-0.50662642 -0.47622473 -1.01864733  0.07395656  1.94429034]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.random.random((5,5))\n",
    "Z = (Z - np.mean (Z)) / (np.std (Z))\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "color = np.dtype([(\"r\", np.ubyte, 1),\n",
    "                  (\"g\", np.ubyte, 1),\n",
    "                  (\"b\", np.ubyte, 1),\n",
    "                  (\"a\", np.ubyte, 1)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[3. 3.]\n",
      " [3. 3.]\n",
      " [3. 3.]\n",
      " [3. 3.]\n",
      " [3. 3.]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.dot(np.ones((5,3)), np.ones((3,2)))\n",
    "print(Z)\n",
    "\n",
    "# Alternative solution, in Python 3.5 and above\n",
    "Z = np.ones((5,3)) @ np.ones((3,2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 0  1  2  3 -4 -5 -6 -7 -8  9 10]\n"
     ]
    }
   ],
   "source": [
    "# Author: Evgeni Burovski\n",
    "\n",
    "Z = np.arange(11)\n",
    "Z[(3 < Z) & (Z <= 8)] *= -1\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 26. What is the output of the following script? (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "# Author: Jake VanderPlas\n",
    "\n",
    "print(sum(range(5),-1))\n",
    "from numpy import *\n",
    "print(sum(range(5),-1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "Integers to negative integer powers are not allowed.",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-27-4e3654d03fce>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mZ\u001b[0m\u001b[1;33m**\u001b[0m\u001b[0mZ\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      2\u001b[0m \u001b[1;36m2\u001b[0m \u001b[1;33m<<\u001b[0m \u001b[0mZ\u001b[0m \u001b[1;33m>>\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0mZ\u001b[0m \u001b[1;33m<\u001b[0m\u001b[1;33m-\u001b[0m \u001b[0mZ\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[1;36m1j\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0mZ\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[0mZ\u001b[0m\u001b[1;33m/\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m/\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mValueError\u001b[0m: Integers to negative integer powers are not allowed."
     ]
    }
   ],
   "source": [
    "Z**Z\n",
    "2 << Z >> 2\n",
    "Z <- Z\n",
    "1j*Z\n",
    "Z/1/1\n",
    "Z<Z>Z"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 28. What are the result of the following expressions?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "nan\n",
      "0\n",
      "[-2.14748365e+09]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in true_divide\n",
      "  \"\"\"Entry point for launching an IPython kernel.\n",
      "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in floor_divide\n",
      "  \n"
     ]
    }
   ],
   "source": [
    "print(np.array(0) / np.array(0))\n",
    "print(np.array(0) // np.array(0))\n",
    "print(np.array([np.nan]).astype(int).astype(float))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 29. How to round away from zero a float array ? (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 6.  6.  8. -9.  7. -9.  9.  8.  2.  4.]\n"
     ]
    }
   ],
   "source": [
    "# Author: Charles R Harris\n",
    "\n",
    "Z = np.random.uniform(-10,+10,10)\n",
    "print (np.copysign(np.ceil(np.abs(Z)), Z))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 30. How to find common values between two arrays? (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 2]\n"
     ]
    }
   ],
   "source": [
    "Z1 = np.random.randint(0,10,10)\n",
    "Z2 = np.random.randint(0,10,10)\n",
    "print(np.intersect1d(Z1,Z2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 31. How to ignore all numpy warnings (not recommended)? (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-31-0437b6d2f8fa>, line 8)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-31-0437b6d2f8fa>\"\u001b[1;36m, line \u001b[1;32m8\u001b[0m\n\u001b[1;33m    An equivalent way, with a context manager:\u001b[0m\n\u001b[1;37m                ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "# Suicide mode on\n",
    "defaults = np.seterr(all=\"ignore\")\n",
    "Z = np.ones(1) / 0\n",
    "\n",
    "# Back to sanity\n",
    "_ = np.seterr(**defaults)\n",
    "\n",
    "An equivalent way, with a context manager:\n",
    "\n",
    "with np.errstate(divide='ignore'):\n",
    "    Z = np.ones(1) / 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 32. Is the following expressions true? (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in sqrt\n",
      "  \"\"\"Entry point for launching an IPython kernel.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.sqrt(-1) == np.emath.sqrt(-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')\n",
    "today     = np.datetime64('today', 'D')\n",
    "tomorrow  = np.datetime64('today', 'D') + np.timedelta64(1, 'D')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 34. How to get all the dates corresponding to the month of July 2016? (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['2016-07-01' '2016-07-02' '2016-07-03' '2016-07-04' '2016-07-05'\n",
      " '2016-07-06' '2016-07-07' '2016-07-08' '2016-07-09' '2016-07-10'\n",
      " '2016-07-11' '2016-07-12' '2016-07-13' '2016-07-14' '2016-07-15'\n",
      " '2016-07-16' '2016-07-17' '2016-07-18' '2016-07-19' '2016-07-20'\n",
      " '2016-07-21' '2016-07-22' '2016-07-23' '2016-07-24' '2016-07-25'\n",
      " '2016-07-26' '2016-07-27' '2016-07-28' '2016-07-29' '2016-07-30'\n",
      " '2016-07-31']\n"
     ]
    }
   ],
   "source": [
    "Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 35. How to compute ((A+B)\\*(-A/2)) in place (without copy)? (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-1.5, -1.5, -1.5])"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A = np.ones(3)*1\n",
    "B = np.ones(3)*2\n",
    "C = np.ones(3)*3\n",
    "np.add(A,B,out=B)\n",
    "np.divide(A,2,out=A)\n",
    "np.negative(A,out=A)\n",
    "np.multiply(A,B,out=A)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 36. Extract the integer part of a random array using 5 different methods (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0. 9. 9. 7. 4. 5. 8. 7. 9. 6.]\n",
      "[0. 9. 9. 7. 4. 5. 8. 7. 9. 6.]\n",
      "[0. 9. 9. 7. 4. 5. 8. 7. 9. 6.]\n",
      "[0 9 9 7 4 5 8 7 9 6]\n",
      "[0. 9. 9. 7. 4. 5. 8. 7. 9. 6.]\n"
     ]
    }
   ],
   "source": [
    "Z = np.random.uniform(0,10,10)\n",
    "\n",
    "print (Z - Z%1)\n",
    "print (np.floor(Z))\n",
    "print (np.ceil(Z)-1)\n",
    "print (Z.astype(int))\n",
    "print (np.trunc(Z))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0. 1. 2. 3. 4.]\n",
      " [0. 1. 2. 3. 4.]\n",
      " [0. 1. 2. 3. 4.]\n",
      " [0. 1. 2. 3. 4.]\n",
      " [0. 1. 2. 3. 4.]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.zeros((5,5))\n",
    "Z += np.arange(5)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]\n"
     ]
    }
   ],
   "source": [
    "def generate():\n",
    "    for x in range(10):\n",
    "        yield x\n",
    "Z = np.fromiter(generate(),dtype=float,count=-1)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455\n",
      " 0.63636364 0.72727273 0.81818182 0.90909091]\n"
     ]
    }
   ],
   "source": [
    "Z = np.linspace(0,1,11,endpoint=False)[1:]\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 40. Create a random vector of size 10 and sort it (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.10181103 0.26965266 0.28134397 0.39484134 0.41394065 0.4810561\n",
      " 0.62636945 0.74893964 0.88528826 0.97455845]\n"
     ]
    }
   ],
   "source": [
    "Z = np.random.random(10)\n",
    "Z.sort()\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 41. How to sum a small array faster than np.sum? (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "45"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Author: Evgeni Burovski\n",
    "\n",
    "Z = np.arange(10)\n",
    "np.add.reduce(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 42. Consider two random array A and B, check if they are equal (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "A = np.random.randint(0,2,5)\n",
    "B = np.random.randint(0,2,5)\n",
    "\n",
    "# Assuming identical shape of the arrays and a tolerance for the comparison of values\n",
    "equal = np.allclose(A,B)\n",
    "print(equal)\n",
    "\n",
    "# Checking both the shape and the element values, no tolerance (values have to be exactly equal)\n",
    "equal = np.array_equal(A,B)\n",
    "print(equal)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 43. Make an array immutable (read-only) (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "assignment destination is read-only",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-43-dcc5e7f145b5>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0mZ\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mzeros\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[0mZ\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mflags\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwriteable\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mFalse\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mZ\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m: assignment destination is read-only"
     ]
    }
   ],
   "source": [
    "Z = np.zeros(10)\n",
    "Z.flags.writeable = False\n",
    "Z[0] = 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.90871086 0.46968371 0.33413258 0.71420399 0.59422443 1.05019902\n",
      " 0.83054677 0.79518205 0.86608232 1.03318804]\n",
      "[1.39381095 0.5465867  0.38210814 0.60935469 0.126408   0.87938679\n",
      " 1.28469889 1.51565796 0.02201551 0.36169143]\n"
     ]
    }
   ],
   "source": [
    "Z = np.random.random((10,2))\n",
    "X,Y = Z[:,0], Z[:,1]\n",
    "R = np.sqrt(X**2+Y**2)\n",
    "T = np.arctan2(Y,X)\n",
    "print(R)\n",
    "print(T)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.50581524 0.25651855 0.01674091 0.88347224 0.73571427 0.44169975\n",
      " 0.65173587 0.84419501 0.         0.70272942]\n"
     ]
    }
   ],
   "source": [
    "Z = np.random.random(10)\n",
    "Z[Z.argmax()] = 0\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 46. Create a structured array with `x` and `y` coordinates covering the \\[0,1\\]x\\[0,1\\] area (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[(0.  , 0.  ) (0.25, 0.  ) (0.5 , 0.  ) (0.75, 0.  ) (1.  , 0.  )]\n",
      " [(0.  , 0.25) (0.25, 0.25) (0.5 , 0.25) (0.75, 0.25) (1.  , 0.25)]\n",
      " [(0.  , 0.5 ) (0.25, 0.5 ) (0.5 , 0.5 ) (0.75, 0.5 ) (1.  , 0.5 )]\n",
      " [(0.  , 0.75) (0.25, 0.75) (0.5 , 0.75) (0.75, 0.75) (1.  , 0.75)]\n",
      " [(0.  , 1.  ) (0.25, 1.  ) (0.5 , 1.  ) (0.75, 1.  ) (1.  , 1.  )]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.zeros((5,5), [('x',float),('y',float)])\n",
    "Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),\n",
    "                             np.linspace(0,1,5))\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "####  47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3638.1636371179666\n"
     ]
    }
   ],
   "source": [
    "# Author: Evgeni Burovski\n",
    "\n",
    "X = np.arange(8)\n",
    "Y = X + 0.5\n",
    "C = 1.0 / np.subtract.outer(X, Y)\n",
    "print(np.linalg.det(C))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-128\n",
      "127\n",
      "-2147483648\n",
      "2147483647\n",
      "-9223372036854775808\n",
      "9223372036854775807\n",
      "-3.4028235e+38\n",
      "3.4028235e+38\n",
      "1.1920929e-07\n",
      "-1.7976931348623157e+308\n",
      "1.7976931348623157e+308\n",
      "2.220446049250313e-16\n"
     ]
    }
   ],
   "source": [
    "for dtype in [np.int8, np.int32, np.int64]:\n",
    "   print(np.iinfo(dtype).min)\n",
    "   print(np.iinfo(dtype).max)\n",
    "for dtype in [np.float32, np.float64]:\n",
    "   print(np.finfo(dtype).min)\n",
    "   print(np.finfo(dtype).max)\n",
    "   print(np.finfo(dtype).eps)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 49. How to print all the values of an array? (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]\n"
     ]
    }
   ],
   "source": [
    "np.set_printoptions(threshold=np.nan)\n",
    "Z = np.zeros((16,16))\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 50. How to find the closest value (to a given scalar) in a vector? (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "39\n"
     ]
    }
   ],
   "source": [
    "Z = np.arange(100)\n",
    "v = np.random.uniform(0,100)\n",
    "index = (np.abs(Z-v)).argmin()\n",
    "print(Z[index])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))\n",
      " ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))\n",
      " ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))\n",
      " ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))\n",
      " ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))]\n"
     ]
    }
   ],
   "source": [
    "Z = np.zeros(10, [ ('position', [ ('x', float, 1),\n",
    "                                  ('y', float, 1)]),\n",
    "                   ('color',    [ ('r', float, 1),\n",
    "                                  ('g', float, 1),\n",
    "                                  ('b', float, 1)])])\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.         0.70858175 0.65599073 0.78907021 0.03919281 0.58217916\n",
      "  0.33731228 0.7468501  0.81072821 0.34085638]\n",
      " [0.70858175 0.         0.59344529 0.09512034 0.71317592 0.25956344\n",
      "  0.80803137 0.53153655 0.36521195 0.63714484]\n",
      " [0.65599073 0.59344529 0.         0.68051235 0.62827887 0.33895441\n",
      "  0.46987665 0.13920127 0.34746751 0.3316422 ]\n",
      " [0.78907021 0.09512034 0.68051235 0.         0.79617326 0.35163036\n",
      "  0.90195864 0.60906462 0.4231078  0.73188727]\n",
      " [0.03919281 0.71317592 0.62827887 0.79617326 0.         0.5731727\n",
      "  0.29812293 0.72361492 0.79714149 0.30801574]\n",
      " [0.58217916 0.25956344 0.33895441 0.35163036 0.5731727  0.\n",
      "  0.58754608 0.30460826 0.24114521 0.40949401]\n",
      " [0.33731228 0.80803137 0.46987665 0.90195864 0.29812293 0.58754608\n",
      "  0.         0.59944019 0.75065963 0.17852171]\n",
      " [0.7468501  0.53153655 0.13920127 0.60906462 0.72361492 0.30460826\n",
      "  0.59944019 0.         0.22570191 0.44636568]\n",
      " [0.81072821 0.36521195 0.34746751 0.4231078  0.79714149 0.24114521\n",
      "  0.75065963 0.22570191 0.         0.57714969]\n",
      " [0.34085638 0.63714484 0.3316422  0.73188727 0.30801574 0.40949401\n",
      "  0.17852171 0.44636568 0.57714969 0.        ]]\n",
      "[[0.         0.21528274 0.6433255  0.33437612 0.28776324 0.14819688\n",
      "  0.34321379 0.54524259 0.68307656 0.0830019 ]\n",
      " [0.21528274 0.         0.44712729 0.27403285 0.32591639 0.28524061\n",
      "  0.33478698 0.35128389 0.49450395 0.16691601]\n",
      " [0.6433255  0.44712729 0.         0.41503631 0.74613255 0.73233626\n",
      "  0.49409743 0.41928663 0.49963719 0.61255203]\n",
      " [0.33437612 0.27403285 0.41503631 0.         0.57318081 0.47403049\n",
      "  0.08658329 0.56115111 0.70031091 0.35760984]\n",
      " [0.28776324 0.32591639 0.74613255 0.57318081 0.         0.16110392\n",
      "  0.60777831 0.46777708 0.57012915 0.22441559]\n",
      " [0.14819688 0.28524061 0.73233626 0.47403049 0.16110392 0.\n",
      "  0.49018431 0.54358417 0.66733094 0.12437018]\n",
      " [0.34321379 0.33478698 0.49409743 0.08658329 0.60777831 0.49018431\n",
      "  0.         0.64241387 0.78297501 0.38468325]\n",
      " [0.54524259 0.35128389 0.41928663 0.56115111 0.46777708 0.54358417\n",
      "  0.64241387 0.         0.14386424 0.470974  ]\n",
      " [0.68307656 0.49450395 0.49963719 0.70031091 0.57012915 0.66733094\n",
      "  0.78297501 0.14386424 0.         0.60610333]\n",
      " [0.0830019  0.16691601 0.61255203 0.35760984 0.22441559 0.12437018\n",
      "  0.38468325 0.470974   0.60610333 0.        ]]\n"
     ]
    }
   ],
   "source": [
    "Z = np.random.random((10,2))\n",
    "X,Y = np.atleast_2d(Z[:,0], Z[:,1])\n",
    "D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)\n",
    "print(D)\n",
    "\n",
    "# Much faster with scipy\n",
    "import scipy\n",
    "# Thanks Gavin Heverly-Coulson (#issue 1)\n",
    "import scipy.spatial\n",
    "\n",
    "Z = np.random.random((10,2))\n",
    "D = scipy.spatial.distance.cdist(Z,Z)\n",
    "print(D)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 53. How to convert a float (32 bits) array into an integer (32 bits) in place?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 1 2 3 4 5 6 7 8 9]\n"
     ]
    }
   ],
   "source": [
    "Z = np.arange(10, dtype=np.float32)\n",
    "Z = Z.astype(np.int32, copy=False)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 54. How to read the following file? (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 1  2  3  4  5]\n",
      " [ 6 -1 -1  7  8]\n",
      " [-1 -1  9 10 11]]\n"
     ]
    }
   ],
   "source": [
    "from io import StringIO\n",
    "\n",
    "# Fake file \n",
    "s = StringIO(\"\"\"1, 2, 3, 4, 5\\n\n",
    "                6,  ,  , 7, 8\\n\n",
    "                 ,  , 9,10,11\\n\"\"\")\n",
    "Z = np.genfromtxt(s, delimiter=\",\", dtype=np.int)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0, 0) 0\n",
      "(0, 1) 1\n",
      "(0, 2) 2\n",
      "(1, 0) 3\n",
      "(1, 1) 4\n",
      "(1, 2) 5\n",
      "(2, 0) 6\n",
      "(2, 1) 7\n",
      "(2, 2) 8\n",
      "(0, 0) 0\n",
      "(0, 1) 1\n",
      "(0, 2) 2\n",
      "(1, 0) 3\n",
      "(1, 1) 4\n",
      "(1, 2) 5\n",
      "(2, 0) 6\n",
      "(2, 1) 7\n",
      "(2, 2) 8\n"
     ]
    }
   ],
   "source": [
    "Z = np.arange(9).reshape(3,3)\n",
    "for index, value in np.ndenumerate(Z):\n",
    "    print(index, value)\n",
    "for index in np.ndindex(Z.shape):\n",
    "    print(index, Z[index])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 56. Generate a generic 2D Gaussian-like array (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.60279818\n",
      "  0.57375342 0.51979489 0.44822088 0.36787944]\n",
      " [0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.73444367\n",
      "  0.69905581 0.63331324 0.54610814 0.44822088]\n",
      " [0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.85172308\n",
      "  0.81068432 0.73444367 0.63331324 0.51979489]\n",
      " [0.57375342 0.69905581 0.81068432 0.89483932 0.9401382  0.9401382\n",
      "  0.89483932 0.81068432 0.69905581 0.57375342]\n",
      " [0.60279818 0.73444367 0.85172308 0.9401382  0.98773022 0.98773022\n",
      "  0.9401382  0.85172308 0.73444367 0.60279818]\n",
      " [0.60279818 0.73444367 0.85172308 0.9401382  0.98773022 0.98773022\n",
      "  0.9401382  0.85172308 0.73444367 0.60279818]\n",
      " [0.57375342 0.69905581 0.81068432 0.89483932 0.9401382  0.9401382\n",
      "  0.89483932 0.81068432 0.69905581 0.57375342]\n",
      " [0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.85172308\n",
      "  0.81068432 0.73444367 0.63331324 0.51979489]\n",
      " [0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.73444367\n",
      "  0.69905581 0.63331324 0.54610814 0.44822088]\n",
      " [0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.60279818\n",
      "  0.57375342 0.51979489 0.44822088 0.36787944]]\n"
     ]
    }
   ],
   "source": [
    "X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))\n",
    "D = np.sqrt(X*X+Y*Y)\n",
    "sigma, mu = 1.0, 0.0\n",
    "G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )\n",
    "print(G)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 57. How to randomly place p elements in a 2D array? (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Divakar\n",
    "\n",
    "n = 10\n",
    "p = 3\n",
    "Z = np.zeros((n,n))\n",
    "np.put(Z, np.random.choice(range(n*n), p, replace=False),1)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 58. Subtract the mean of each row of a matrix (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.08728985  0.34574179 -0.07096404 -0.35665903  0.27195823 -0.21226241\n",
      "  -0.05786562  0.46226838 -0.51113477  0.04162763]\n",
      " [ 0.15769693 -0.00687416 -0.23088468 -0.27531393 -0.15748372  0.49855641\n",
      "  -0.29182386  0.23153223  0.1335274  -0.05893261]\n",
      " [-0.19887161 -0.08551958  0.13483777  0.4249683   0.32140219 -0.01568819\n",
      "  -0.25863495 -0.19687856  0.0745396  -0.20015498]\n",
      " [ 0.05544274  0.23450517 -0.25309467  0.00991447 -0.50428326 -0.09024474\n",
      "   0.01610101  0.4324277   0.13499273 -0.03576114]\n",
      " [ 0.08014561  0.44307603 -0.54198293 -0.15386254  0.377373    0.24122398\n",
      "  -0.4620369  -0.03100136  0.21078297 -0.16371787]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Warren Weckesser\n",
    "\n",
    "X = np.random.rand(5, 10)\n",
    "\n",
    "# Recent versions of numpy\n",
    "Y = X - X.mean(axis=1, keepdims=True)\n",
    "\n",
    "# Older versions of numpy\n",
    "Y = X - X.mean(axis=1).reshape(-1, 1)\n",
    "\n",
    "print(Y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 59. How to sort an array by the nth column? (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[2 9 2]\n",
      " [5 7 9]\n",
      " [0 8 1]]\n",
      "[[5 7 9]\n",
      " [0 8 1]\n",
      " [2 9 2]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Steve Tjoa\n",
    "\n",
    "Z = np.random.randint(0,10,(3,3))\n",
    "print(Z)\n",
    "print(Z[Z[:,1].argsort()])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 60. How to tell if a given 2D array has null columns? (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n"
     ]
    }
   ],
   "source": [
    "# Author: Warren Weckesser\n",
    "\n",
    "Z = np.random.randint(0,3,(3,10))\n",
    "print((~Z.any(axis=0)).any())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 61. Find the nearest value from a given value in an array (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.3388283390062511\n"
     ]
    }
   ],
   "source": [
    "Z = np.random.uniform(0,1,10)\n",
    "z = 0.5\n",
    "m = Z.flat[np.abs(Z - z).argmin()]\n",
    "print(m)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 1 2]\n",
      " [1 2 3]\n",
      " [2 3 4]]\n"
     ]
    }
   ],
   "source": [
    "A = np.arange(3).reshape(3,1)\n",
    "B = np.arange(3).reshape(1,3)\n",
    "it = np.nditer([A,B,None])\n",
    "for x,y,z in it: z[...] = x + y\n",
    "print(it.operands[2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 63. Create an array class that has a name attribute (★★☆)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "range_10\n"
     ]
    }
   ],
   "source": [
    "class NamedArray(np.ndarray):\n",
    "    def __new__(cls, array, name=\"no name\"):\n",
    "        obj = np.asarray(array).view(cls)\n",
    "        obj.name = name\n",
    "        return obj\n",
    "    def __array_finalize__(self, obj):\n",
    "        if obj is None: return\n",
    "        self.info = getattr(obj, 'name', \"no name\")\n",
    "\n",
    "Z = NamedArray(np.arange(10), \"range_10\")\n",
    "print (Z.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2. 5. 4. 1. 1. 4. 3. 2. 5. 3.]\n",
      "[3. 9. 7. 1. 1. 7. 5. 3. 9. 5.]\n"
     ]
    }
   ],
   "source": [
    "# Author: Brett Olsen\n",
    "\n",
    "Z = np.ones(10)\n",
    "I = np.random.randint(0,len(Z),20)\n",
    "Z += np.bincount(I, minlength=len(Z))\n",
    "print(Z)\n",
    "\n",
    "# Another solution\n",
    "# Author: Bartosz Telenczuk\n",
    "np.add.at(Z, I, 1)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0. 7. 0. 6. 5. 0. 0. 0. 0. 3.]\n"
     ]
    }
   ],
   "source": [
    "# Author: Alan G Isaac\n",
    "\n",
    "X = [1,2,3,4,5,6]\n",
    "I = [1,3,9,3,4,1]\n",
    "F = np.bincount(I,X)\n",
    "print(F)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8\n"
     ]
    }
   ],
   "source": [
    "# Author: Nadav Horesh\n",
    "\n",
    "w,h = 16,16\n",
    "I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)\n",
    "#Note that we should compute 256*256 first. \n",
    "#Otherwise numpy will only promote F.dtype to 'uint16' and overfolw will occur\n",
    "F = I[...,0]*(256*256) + I[...,1]*256 +I[...,2]\n",
    "n = len(np.unique(F))\n",
    "print(n)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[67 54 59 65]\n",
      " [71 59 49 46]\n",
      " [40 46 48 44]]\n",
      "[[67 54 59 65]\n",
      " [71 59 49 46]\n",
      " [40 46 48 44]]\n"
     ]
    }
   ],
   "source": [
    "A = np.random.randint(0,10,(3,4,3,4))\n",
    "# solution by passing a tuple of axes (introduced in numpy 1.7.0)\n",
    "sum = A.sum(axis=(-2,-1))\n",
    "print(sum)\n",
    "# solution by flattening the last two dimensions into one\n",
    "# (useful for functions that don't accept tuples for axis argument)\n",
    "sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)\n",
    "print(sum)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset  indices? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.36435063 0.49399621 0.41187814 0.55834713 0.50337821 0.59980105\n",
      " 0.54636651 0.62150694 0.46052147 0.55536347]\n",
      "0    0.364351\n",
      "1    0.493996\n",
      "2    0.411878\n",
      "3    0.558347\n",
      "4    0.503378\n",
      "5    0.599801\n",
      "6    0.546367\n",
      "7    0.621507\n",
      "8    0.460521\n",
      "9    0.555363\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "# Author: Jaime Fernández del Río\n",
    "\n",
    "D = np.random.uniform(0,1,100)\n",
    "S = np.random.randint(0,10,100)\n",
    "D_sums = np.bincount(S, weights=D)\n",
    "D_counts = np.bincount(S)\n",
    "D_means = D_sums / D_counts\n",
    "print(D_means)\n",
    "\n",
    "# Pandas solution as a reference due to more intuitive code\n",
    "import pandas as pd\n",
    "print(pd.Series(D).groupby(S).mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 69. How to get the diagonal of a dot product? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1.43740433, 1.30533245, 1.32379824, 2.46896817, 0.67545867])"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Author: Mathieu Blondel\n",
    "\n",
    "A = np.random.uniform(0,1,(5,5))\n",
    "B = np.random.uniform(0,1,(5,5))\n",
    "\n",
    "# Slow version  \n",
    "np.diag(np.dot(A, B))\n",
    "\n",
    "# Fast version\n",
    "np.sum(A * B.T, axis=1)\n",
    "\n",
    "# Faster version\n",
    "np.einsum(\"ij,ji->i\", A, B)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 70. Consider the vector \\[1, 2, 3, 4, 5\\], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1. 0. 0. 0. 2. 0. 0. 0. 3. 0. 0. 0. 4. 0. 0. 0. 5.]\n"
     ]
    }
   ],
   "source": [
    "# Author: Warren Weckesser\n",
    "\n",
    "Z = np.array([1,2,3,4,5])\n",
    "nz = 3\n",
    "Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))\n",
    "Z0[::nz+1] = Z\n",
    "print(Z0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]]\n",
      "\n",
      " [[2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]]\n",
      "\n",
      " [[2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]]\n",
      "\n",
      " [[2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]]\n",
      "\n",
      " [[2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]\n",
      "  [2. 2. 2.]]]\n"
     ]
    }
   ],
   "source": [
    "A = np.ones((5,5,3))\n",
    "B = 2*np.ones((5,5))\n",
    "print(A * B[:,:,None])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 72. How to swap two rows of an array? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 5  6  7  8  9]\n",
      " [ 0  1  2  3  4]\n",
      " [10 11 12 13 14]\n",
      " [15 16 17 18 19]\n",
      " [20 21 22 23 24]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Eelco Hoogendoorn\n",
    "\n",
    "A = np.arange(25).reshape(5,5)\n",
    "A[[0,1]] = A[[1,0]]\n",
    "print(A)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the  triangles (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[( 0,  9) ( 0, 11) ( 0, 59) ( 0, 91) ( 1,  8) ( 1, 47) ( 1, 69) ( 1, 82)\n",
      " ( 3, 40) ( 3, 97) ( 5,  9) ( 5, 73) ( 8, 47) ( 9, 11) ( 9, 73) (13, 53)\n",
      " (13, 56) (13, 58) (13, 99) (16, 62) (16, 82) (28, 84) (28, 87) (40, 97)\n",
      " (53, 99) (56, 58) (59, 91) (62, 82) (69, 82) (84, 87)]\n"
     ]
    }
   ],
   "source": [
    "# Author: Nicolas P. Rougier\n",
    "\n",
    "faces = np.random.randint(0,100,(10,3))\n",
    "F = np.roll(faces.repeat(2,axis=1),-1,axis=1)\n",
    "F = F.reshape(len(F)*3,2)\n",
    "F = np.sort(F,axis=1)\n",
    "G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )\n",
    "G = np.unique(G)\n",
    "print(G)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 1 2 3 4 4 6]\n"
     ]
    }
   ],
   "source": [
    "# Author: Jaime Fernández del Río\n",
    "\n",
    "C = np.bincount([1,1,2,3,4,4,6])\n",
    "A = np.repeat(np.arange(len(C)), C)\n",
    "print(A)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 75. How to compute averages using a sliding window over an array? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14. 15. 16. 17. 18.]\n"
     ]
    }
   ],
   "source": [
    "# Author: Jaime Fernández del Río\n",
    "\n",
    "def moving_average(a, n=3) :\n",
    "    ret = np.cumsum(a, dtype=float)\n",
    "    ret[n:] = ret[n:] - ret[:-n]\n",
    "    return ret[n - 1:] / n\n",
    "Z = np.arange(20)\n",
    "print(moving_average(Z, n=3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z\\[0\\],Z\\[1\\],Z\\[2\\]) and each subsequent row is  shifted by 1 (last row should be (Z\\[-3\\],Z\\[-2\\],Z\\[-1\\]) (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 1 2]\n",
      " [1 2 3]\n",
      " [2 3 4]\n",
      " [3 4 5]\n",
      " [4 5 6]\n",
      " [5 6 7]\n",
      " [6 7 8]\n",
      " [7 8 9]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Joe Kington / Erik Rigtorp\n",
    "from numpy.lib import stride_tricks\n",
    "\n",
    "def rolling(a, window):\n",
    "    shape = (a.size - window + 1, window)\n",
    "    strides = (a.itemsize, a.itemsize)\n",
    "    return stride_tricks.as_strided(a, shape=shape, strides=strides)\n",
    "Z = rolling(np.arange(10), 3)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.61458663, -0.83229834,  0.15687329,  0.86684934, -0.80418945,\n",
       "       -0.94400753,  0.68204938, -0.40034997,  0.56881214,  0.60763882,\n",
       "       -0.41558119, -0.96786492, -0.29382729, -0.43597838,  0.46867397,\n",
       "       -0.73113098, -0.31367014,  0.50218112, -0.18159377, -0.03321331,\n",
       "        0.93574029,  0.95764592,  0.83438669,  0.93493816,  0.27413529,\n",
       "        0.79686667,  0.21453622, -0.34477178, -0.90442065, -0.28982899,\n",
       "       -0.22376251,  0.7821683 ,  0.80871286,  0.09547893,  0.65898887,\n",
       "       -0.50329235,  0.70567483,  0.7260582 ,  0.29526807, -0.61692596,\n",
       "       -0.06398481,  0.38447694, -0.20192775, -0.776956  , -0.86298302,\n",
       "        0.62069504,  0.7156818 , -0.16731062, -0.67338785,  0.9475525 ,\n",
       "        0.78363151, -0.68028943,  0.37714017,  0.99798309,  0.09080988,\n",
       "        0.22431419,  0.44528906,  0.27134833, -0.17727835, -0.64134425,\n",
       "       -0.26404034, -0.10714442,  0.04077127,  0.76593247, -0.26830685,\n",
       "        0.81933781, -0.14372722, -0.78525057, -0.03657832, -0.0838801 ,\n",
       "       -0.9998223 , -0.57809221,  0.62441487, -0.91798214, -0.20347455,\n",
       "        0.89401068, -0.36615874,  0.35508649, -0.988561  , -0.42155252,\n",
       "       -0.79222461, -0.38832939,  0.65991297,  0.09981309, -0.26838381,\n",
       "       -0.61731762,  0.470328  ,  0.36521011, -0.04780786,  0.52860473,\n",
       "        0.44800137,  0.18834723, -0.90079054, -0.03385857,  0.72054287,\n",
       "        0.98253035, -0.93777418,  0.86997239,  0.98122332, -0.4601323 ])"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Author: Nathaniel J. Smith\n",
    "\n",
    "Z = np.random.randint(0,2,100)\n",
    "np.logical_not(Z, out=Z)\n",
    "\n",
    "Z = np.random.uniform(-1.0,1.0,100)\n",
    "np.negative(Z, out=Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i  (P0\\[i\\],P1\\[i\\])? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3.70672797 7.69612039 2.25784974 4.60168732 1.86333395 0.34324433\n",
      " 0.81905363 1.00428102 4.4882624  5.52240104]\n"
     ]
    }
   ],
   "source": [
    "def distance(P0, P1, p):\n",
    "    T = P1 - P0\n",
    "    L = (T**2).sum(axis=1)\n",
    "    U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L\n",
    "    U = U.reshape(len(U),1)\n",
    "    D = P0 + U*T - p\n",
    "    return np.sqrt((D**2).sum(axis=1))\n",
    "\n",
    "P0 = np.random.uniform(-10,10,(10,2))\n",
    "P1 = np.random.uniform(-10,10,(10,2))\n",
    "p  = np.random.uniform(-10,10,( 1,2))\n",
    "print(distance(P0, P1, p))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 79. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P\\[j\\]) to each line i (P0\\[i\\],P1\\[i\\])? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 3.51631169  6.42167595  4.90471349  8.92152608  0.64430522 13.1477316\n",
      "   4.82647115 14.35803776  2.83869333  5.78536237]\n",
      " [11.72333193  2.28525701  4.48035411 11.29872486 14.10963053  4.49070061\n",
      "   6.06173032  5.24835195  3.32272461 11.12005469]\n",
      " [ 7.68423685  3.99209265 12.25140797  4.74391157  4.67770228  5.40024792\n",
      "   5.31689533  8.63226702  7.63625936  2.4274878 ]\n",
      " [ 4.72217595  8.25441437  1.85343282  1.41186727  8.5013649   8.04308066\n",
      "   3.56471625  7.66668404  3.79347479  1.17033352]\n",
      " [ 4.61970509  1.82880232  0.88155845  3.87855982  7.49446718  1.13451433\n",
      "   3.69653461  1.60058913  2.96229578  5.89123061]\n",
      " [ 1.71064014  2.13236159  2.87428566  0.42743983  4.85508373  3.972235\n",
      "   2.17049563  4.87642258  2.29807957  3.20458539]\n",
      " [ 1.10951331  3.52006522  2.73748642  1.39980831  4.49782435  6.00139265\n",
      "   0.34929072  6.82585741  0.76526847  1.17624526]\n",
      " [ 0.56577927  0.63802769  4.85499764  1.49919907  3.40600949  1.94224115\n",
      "   4.85430884  3.39018238  5.08047535  5.36034047]\n",
      " [ 4.08155314  4.50758583  9.84132717  0.35258316  1.4288174   1.73395701\n",
      "   7.36540087  4.4413348   8.60583634  5.90988377]\n",
      " [ 7.15223448 10.7222427   4.64476979  0.81731108 11.09257472  8.63596863\n",
      "   5.38289103  7.54390954  6.10500134  1.95186145]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Italmassov Kuanysh\n",
    "\n",
    "# based on distance function from previous question\n",
    "P0 = np.random.uniform(-10, 10, (10,2))\n",
    "P1 = np.random.uniform(-10,10,(10,2))\n",
    "p = np.random.uniform(-10, 10, (10,2))\n",
    "print(np.array([distance(P0,P1,p_i) for p_i in p]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 80. Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[4 3 2 8 2 6 7 3 0 8]\n",
      " [8 9 7 6 1 5 2 4 6 1]\n",
      " [1 6 2 0 2 4 0 3 4 8]\n",
      " [8 0 8 0 8 4 6 3 3 1]\n",
      " [6 0 4 9 5 3 0 5 3 0]\n",
      " [6 7 5 4 3 7 9 0 9 6]\n",
      " [7 1 8 4 1 9 0 8 8 0]\n",
      " [7 8 4 9 4 0 0 6 5 7]\n",
      " [9 3 5 8 7 2 6 5 5 7]\n",
      " [7 9 6 7 8 7 7 8 8 7]]\n",
      "[[0 0 0 0 0]\n",
      " [0 4 3 2 8]\n",
      " [0 8 9 7 6]\n",
      " [0 1 6 2 0]\n",
      " [0 8 0 8 0]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Nicolas Rougier\n",
    "\n",
    "Z = np.random.randint(0,10,(10,10))\n",
    "shape = (5,5)\n",
    "fill  = 0\n",
    "position = (1,1)\n",
    "\n",
    "R = np.ones(shape, dtype=Z.dtype)*fill\n",
    "P  = np.array(list(position)).astype(int)\n",
    "Rs = np.array(list(R.shape)).astype(int)\n",
    "Zs = np.array(list(Z.shape)).astype(int)\n",
    "\n",
    "R_start = np.zeros((len(shape),)).astype(int)\n",
    "R_stop  = np.array(list(shape)).astype(int)\n",
    "Z_start = (P-Rs//2)\n",
    "Z_stop  = (P+Rs//2)+Rs%2\n",
    "\n",
    "R_start = (R_start - np.minimum(Z_start,0)).tolist()\n",
    "Z_start = (np.maximum(Z_start,0)).tolist()\n",
    "R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()\n",
    "Z_stop = (np.minimum(Z_stop,Zs)).tolist()\n",
    "\n",
    "r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]\n",
    "z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]\n",
    "R[r] = Z[z]\n",
    "print(Z)\n",
    "print(R)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 81. Consider an array Z = \\[1,2,3,4,5,6,7,8,9,10,11,12,13,14\\], how to generate an array R = \\[\\[1,2,3,4\\], \\[2,3,4,5\\], \\[3,4,5,6\\], ..., \\[11,12,13,14\\]\\]? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 1  2  3  4]\n",
      " [ 2  3  4  5]\n",
      " [ 3  4  5  6]\n",
      " [ 4  5  6  7]\n",
      " [ 5  6  7  8]\n",
      " [ 6  7  8  9]\n",
      " [ 7  8  9 10]\n",
      " [ 8  9 10 11]\n",
      " [ 9 10 11 12]\n",
      " [10 11 12 13]\n",
      " [11 12 13 14]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Stefan van der Walt\n",
    "\n",
    "Z = np.arange(1,15,dtype=np.uint32)\n",
    "R = stride_tricks.as_strided(Z,(11,4),(4,4))\n",
    "print(R)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 82. Compute a matrix rank (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n"
     ]
    }
   ],
   "source": [
    "# Author: Stefan van der Walt\n",
    "\n",
    "Z = np.random.uniform(0,1,(10,10))\n",
    "U, S, V = np.linalg.svd(Z) # Singular Value Decomposition\n",
    "rank = np.sum(S > 1e-10)\n",
    "print(rank)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 83. How to find the most frequent value in an array?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n"
     ]
    }
   ],
   "source": [
    "Z = np.random.randint(0,10,50)\n",
    "print(np.bincount(Z).argmax())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[[0 0 2]\n",
      "   [4 3 4]\n",
      "   [4 2 4]]\n",
      "\n",
      "  [[0 2 0]\n",
      "   [3 4 0]\n",
      "   [2 4 3]]\n",
      "\n",
      "  [[2 0 1]\n",
      "   [4 0 0]\n",
      "   [4 3 3]]\n",
      "\n",
      "  [[0 1 1]\n",
      "   [0 0 0]\n",
      "   [3 3 2]]\n",
      "\n",
      "  [[1 1 0]\n",
      "   [0 0 1]\n",
      "   [3 2 4]]\n",
      "\n",
      "  [[1 0 4]\n",
      "   [0 1 3]\n",
      "   [2 4 1]]\n",
      "\n",
      "  [[0 4 2]\n",
      "   [1 3 4]\n",
      "   [4 1 1]]\n",
      "\n",
      "  [[4 2 2]\n",
      "   [3 4 4]\n",
      "   [1 1 3]]]\n",
      "\n",
      "\n",
      " [[[4 3 4]\n",
      "   [4 2 4]\n",
      "   [3 0 3]]\n",
      "\n",
      "  [[3 4 0]\n",
      "   [2 4 3]\n",
      "   [0 3 0]]\n",
      "\n",
      "  [[4 0 0]\n",
      "   [4 3 3]\n",
      "   [3 0 3]]\n",
      "\n",
      "  [[0 0 0]\n",
      "   [3 3 2]\n",
      "   [0 3 4]]\n",
      "\n",
      "  [[0 0 1]\n",
      "   [3 2 4]\n",
      "   [3 4 2]]\n",
      "\n",
      "  [[0 1 3]\n",
      "   [2 4 1]\n",
      "   [4 2 2]]\n",
      "\n",
      "  [[1 3 4]\n",
      "   [4 1 1]\n",
      "   [2 2 0]]\n",
      "\n",
      "  [[3 4 4]\n",
      "   [1 1 3]\n",
      "   [2 0 2]]]\n",
      "\n",
      "\n",
      " [[[4 2 4]\n",
      "   [3 0 3]\n",
      "   [2 4 3]]\n",
      "\n",
      "  [[2 4 3]\n",
      "   [0 3 0]\n",
      "   [4 3 0]]\n",
      "\n",
      "  [[4 3 3]\n",
      "   [3 0 3]\n",
      "   [3 0 3]]\n",
      "\n",
      "  [[3 3 2]\n",
      "   [0 3 4]\n",
      "   [0 3 3]]\n",
      "\n",
      "  [[3 2 4]\n",
      "   [3 4 2]\n",
      "   [3 3 1]]\n",
      "\n",
      "  [[2 4 1]\n",
      "   [4 2 2]\n",
      "   [3 1 2]]\n",
      "\n",
      "  [[4 1 1]\n",
      "   [2 2 0]\n",
      "   [1 2 1]]\n",
      "\n",
      "  [[1 1 3]\n",
      "   [2 0 2]\n",
      "   [2 1 3]]]\n",
      "\n",
      "\n",
      " [[[3 0 3]\n",
      "   [2 4 3]\n",
      "   [3 0 4]]\n",
      "\n",
      "  [[0 3 0]\n",
      "   [4 3 0]\n",
      "   [0 4 1]]\n",
      "\n",
      "  [[3 0 3]\n",
      "   [3 0 3]\n",
      "   [4 1 1]]\n",
      "\n",
      "  [[0 3 4]\n",
      "   [0 3 3]\n",
      "   [1 1 4]]\n",
      "\n",
      "  [[3 4 2]\n",
      "   [3 3 1]\n",
      "   [1 4 1]]\n",
      "\n",
      "  [[4 2 2]\n",
      "   [3 1 2]\n",
      "   [4 1 3]]\n",
      "\n",
      "  [[2 2 0]\n",
      "   [1 2 1]\n",
      "   [1 3 0]]\n",
      "\n",
      "  [[2 0 2]\n",
      "   [2 1 3]\n",
      "   [3 0 1]]]\n",
      "\n",
      "\n",
      " [[[2 4 3]\n",
      "   [3 0 4]\n",
      "   [0 2 2]]\n",
      "\n",
      "  [[4 3 0]\n",
      "   [0 4 1]\n",
      "   [2 2 0]]\n",
      "\n",
      "  [[3 0 3]\n",
      "   [4 1 1]\n",
      "   [2 0 4]]\n",
      "\n",
      "  [[0 3 3]\n",
      "   [1 1 4]\n",
      "   [0 4 3]]\n",
      "\n",
      "  [[3 3 1]\n",
      "   [1 4 1]\n",
      "   [4 3 4]]\n",
      "\n",
      "  [[3 1 2]\n",
      "   [4 1 3]\n",
      "   [3 4 0]]\n",
      "\n",
      "  [[1 2 1]\n",
      "   [1 3 0]\n",
      "   [4 0 2]]\n",
      "\n",
      "  [[2 1 3]\n",
      "   [3 0 1]\n",
      "   [0 2 1]]]\n",
      "\n",
      "\n",
      " [[[3 0 4]\n",
      "   [0 2 2]\n",
      "   [1 3 4]]\n",
      "\n",
      "  [[0 4 1]\n",
      "   [2 2 0]\n",
      "   [3 4 1]]\n",
      "\n",
      "  [[4 1 1]\n",
      "   [2 0 4]\n",
      "   [4 1 0]]\n",
      "\n",
      "  [[1 1 4]\n",
      "   [0 4 3]\n",
      "   [1 0 1]]\n",
      "\n",
      "  [[1 4 1]\n",
      "   [4 3 4]\n",
      "   [0 1 0]]\n",
      "\n",
      "  [[4 1 3]\n",
      "   [3 4 0]\n",
      "   [1 0 1]]\n",
      "\n",
      "  [[1 3 0]\n",
      "   [4 0 2]\n",
      "   [0 1 4]]\n",
      "\n",
      "  [[3 0 1]\n",
      "   [0 2 1]\n",
      "   [1 4 1]]]\n",
      "\n",
      "\n",
      " [[[0 2 2]\n",
      "   [1 3 4]\n",
      "   [2 0 1]]\n",
      "\n",
      "  [[2 2 0]\n",
      "   [3 4 1]\n",
      "   [0 1 2]]\n",
      "\n",
      "  [[2 0 4]\n",
      "   [4 1 0]\n",
      "   [1 2 2]]\n",
      "\n",
      "  [[0 4 3]\n",
      "   [1 0 1]\n",
      "   [2 2 0]]\n",
      "\n",
      "  [[4 3 4]\n",
      "   [0 1 0]\n",
      "   [2 0 0]]\n",
      "\n",
      "  [[3 4 0]\n",
      "   [1 0 1]\n",
      "   [0 0 4]]\n",
      "\n",
      "  [[4 0 2]\n",
      "   [0 1 4]\n",
      "   [0 4 0]]\n",
      "\n",
      "  [[0 2 1]\n",
      "   [1 4 1]\n",
      "   [4 0 1]]]\n",
      "\n",
      "\n",
      " [[[1 3 4]\n",
      "   [2 0 1]\n",
      "   [2 4 2]]\n",
      "\n",
      "  [[3 4 1]\n",
      "   [0 1 2]\n",
      "   [4 2 3]]\n",
      "\n",
      "  [[4 1 0]\n",
      "   [1 2 2]\n",
      "   [2 3 1]]\n",
      "\n",
      "  [[1 0 1]\n",
      "   [2 2 0]\n",
      "   [3 1 4]]\n",
      "\n",
      "  [[0 1 0]\n",
      "   [2 0 0]\n",
      "   [1 4 2]]\n",
      "\n",
      "  [[1 0 1]\n",
      "   [0 0 4]\n",
      "   [4 2 0]]\n",
      "\n",
      "  [[0 1 4]\n",
      "   [0 4 0]\n",
      "   [2 0 3]]\n",
      "\n",
      "  [[1 4 1]\n",
      "   [4 0 1]\n",
      "   [0 3 3]]]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Chris Barker\n",
    "\n",
    "Z = np.random.randint(0,5,(10,10))\n",
    "n = 3\n",
    "i = 1 + (Z.shape[0]-3)\n",
    "j = 1 + (Z.shape[1]-3)\n",
    "C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)\n",
    "print(C)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 85. Create a 2D array subclass such that Z\\[i,j\\] == Z\\[j,i\\] (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 1 16  6  5  6]\n",
      " [16  5 13 16 12]\n",
      " [ 6 13  4 42  2]\n",
      " [ 5 16 42  2 13]\n",
      " [ 6 12  2 13  3]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Eric O. Lebigot\n",
    "# Note: only works for 2d array and value setting using indices\n",
    "\n",
    "class Symetric(np.ndarray):\n",
    "    def __setitem__(self, index, value):\n",
    "        i,j = index\n",
    "        super(Symetric, self).__setitem__((i,j), value)\n",
    "        super(Symetric, self).__setitem__((j,i), value)\n",
    "\n",
    "def symetric(Z):\n",
    "    return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)\n",
    "\n",
    "S = symetric(np.random.randint(0,10,(5,5)))\n",
    "S[2,3] = 42\n",
    "print(S)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 86. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]\n",
      " [200.]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Stefan van der Walt\n",
    "\n",
    "p, n = 10, 20\n",
    "M = np.ones((p,n,n))\n",
    "V = np.ones((p,n,1))\n",
    "S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])\n",
    "print(S)\n",
    "\n",
    "# It works, because:\n",
    "# M is (p,n,n)\n",
    "# V is (p,n,1)\n",
    "# Thus, summing over the paired axes 0 and 0 (of M and V independently),\n",
    "# and 2 and 1, to remain with a (n,1) vector."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[16. 16. 16. 16.]\n",
      " [16. 16. 16. 16.]\n",
      " [16. 16. 16. 16.]\n",
      " [16. 16. 16. 16.]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Robert Kern\n",
    "\n",
    "Z = np.ones((16,16))\n",
    "k = 4\n",
    "S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),\n",
    "                                       np.arange(0, Z.shape[1], k), axis=1)\n",
    "print(S)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 88. How to implement the Game of Life using numpy arrays? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 1 0\n",
      "  0 0 0 0 0 1 1 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0\n",
      "  0 0 0 0 0 1 1 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 1 1 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  1 1 0 0 0 0 0 0 1 1 1 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1\n",
      "  0 0 1 0 0 0 0 0 1 1 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0\n",
      "  1 1 0 0 0 0 0 0 1 0 1 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 1 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 1 0 0 0 1 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 1 0 0 0 1 1 1 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 1 0 0 1 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 1 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 1 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 1 0 1 0 0 1 1 0 0 1 1 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 1 0 0 1 0 0 0 1 1 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 1 0 0 0 1 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 1 0 0 1 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 1 0 1 1 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 1 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 1 1 1 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 1 0 1 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0\n",
      "  0 0 1 0 0 1 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 1 1 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 1 0 1 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 1 1 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      "  0 0 0 0 0 0 0 0 0 0 0 0 0 0]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Nicolas Rougier\n",
    "\n",
    "def iterate(Z):\n",
    "    # Count neighbours\n",
    "    N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +\n",
    "         Z[1:-1,0:-2]                + Z[1:-1,2:] +\n",
    "         Z[2:  ,0:-2] + Z[2:  ,1:-1] + Z[2:  ,2:])\n",
    "\n",
    "    # Apply rules\n",
    "    birth = (N==3) & (Z[1:-1,1:-1]==0)\n",
    "    survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1)\n",
    "    Z[...] = 0\n",
    "    Z[1:-1,1:-1][birth | survive] = 1\n",
    "    return Z\n",
    "\n",
    "Z = np.random.randint(0,2,(50,50))\n",
    "for i in range(100): Z = iterate(Z)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 89. How to get the n largest values of an array (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[9995 9996 9997 9998 9999]\n",
      "[9998 9999 9997 9996 9995]\n"
     ]
    }
   ],
   "source": [
    "Z = np.arange(10000)\n",
    "np.random.shuffle(Z)\n",
    "n = 5\n",
    "\n",
    "# Slow\n",
    "print (Z[np.argsort(Z)[-n:]])\n",
    "\n",
    "# Fast\n",
    "print (Z[np.argpartition(-Z,n)[:n]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 4 6]\n",
      " [1 4 7]\n",
      " [1 5 6]\n",
      " [1 5 7]\n",
      " [2 4 6]\n",
      " [2 4 7]\n",
      " [2 5 6]\n",
      " [2 5 7]\n",
      " [3 4 6]\n",
      " [3 4 7]\n",
      " [3 5 6]\n",
      " [3 5 7]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Stefan Van der Walt\n",
    "\n",
    "def cartesian(arrays):\n",
    "    arrays = [np.asarray(a) for a in arrays]\n",
    "    shape = (len(x) for x in arrays)\n",
    "\n",
    "    ix = np.indices(shape, dtype=int)\n",
    "    ix = ix.reshape(len(arrays), -1).T\n",
    "\n",
    "    for n, arr in enumerate(arrays):\n",
    "        ix[:, n] = arrays[n][ix[:, n]]\n",
    "\n",
    "    return ix\n",
    "\n",
    "print (cartesian(([1, 2, 3], [4, 5], [6, 7])))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 91. How to create a record array from a regular array? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(b'Hello', 2.5, 3) (b'World', 3.6, 2)]\n"
     ]
    }
   ],
   "source": [
    "Z = np.array([(\"Hello\", 2.5, 3),\n",
    "              (\"World\", 3.6, 2)])\n",
    "R = np.core.records.fromarrays(Z.T, \n",
    "                               names='col1, col2, col3',\n",
    "                               formats = 'S8, f8, i8')\n",
    "print(R)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'float' object cannot be interpreted as an integer",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-92-4526b6c58168>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;31m# Author: Ryan G.\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mx\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrandom\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrand\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m5e7\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[0mget_ipython\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrun_line_magic\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'timeit'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'np.power(x,3)'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mmtrand.pyx\u001b[0m in \u001b[0;36mmtrand.RandomState.rand\u001b[1;34m()\u001b[0m\n",
      "\u001b[1;32mmtrand.pyx\u001b[0m in \u001b[0;36mmtrand.RandomState.random_sample\u001b[1;34m()\u001b[0m\n",
      "\u001b[1;32mmtrand.pyx\u001b[0m in \u001b[0;36mmtrand.cont0_array\u001b[1;34m()\u001b[0m\n",
      "\u001b[1;31mTypeError\u001b[0m: 'float' object cannot be interpreted as an integer"
     ]
    }
   ],
   "source": [
    "# Author: Ryan G.\n",
    "\n",
    "x = np.random.rand(5e7)\n",
    "\n",
    "%timeit np.power(x,3)\n",
    "%timeit x*x*x\n",
    "%timeit np.einsum('i,i,i->i',x,x,x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 93. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[]\n"
     ]
    }
   ],
   "source": [
    "# Author: Gabe Schwartz\n",
    "\n",
    "A = np.random.randint(0,5,(8,3))\n",
    "B = np.random.randint(0,5,(2,2))\n",
    "\n",
    "C = (A[..., np.newaxis, np.newaxis] == B)\n",
    "rows = np.where(C.any((3,1)).all(1))[0]\n",
    "print(rows)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. \\[2,2,3\\]) (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 1 1]\n",
      " [3 4 1]\n",
      " [0 2 4]\n",
      " [4 1 4]\n",
      " [3 4 4]\n",
      " [3 2 1]\n",
      " [3 0 3]\n",
      " [2 1 0]\n",
      " [3 0 3]\n",
      " [0 1 2]]\n",
      "[[3 4 1]\n",
      " [0 2 4]\n",
      " [4 1 4]\n",
      " [3 4 4]\n",
      " [3 2 1]\n",
      " [3 0 3]\n",
      " [2 1 0]\n",
      " [3 0 3]\n",
      " [0 1 2]]\n",
      "[[3 4 1]\n",
      " [0 2 4]\n",
      " [4 1 4]\n",
      " [3 4 4]\n",
      " [3 2 1]\n",
      " [3 0 3]\n",
      " [2 1 0]\n",
      " [3 0 3]\n",
      " [0 1 2]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Robert Kern\n",
    "\n",
    "Z = np.random.randint(0,5,(10,3))\n",
    "print(Z)\n",
    "# solution for arrays of all dtypes (including string arrays and record arrays)\n",
    "E = np.all(Z[:,1:] == Z[:,:-1], axis=1)\n",
    "U = Z[~E]\n",
    "print(U)\n",
    "# soluiton for numerical arrays only, will work for any number of columns in Z\n",
    "U = Z[Z.max(axis=1) != Z.min(axis=1),:]\n",
    "print(U)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 95. Convert a vector of ints into a matrix binary representation (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 1]\n",
      " [0 0 0 0 0 0 1 0]\n",
      " [0 0 0 0 0 0 1 1]\n",
      " [0 0 0 0 1 1 1 1]\n",
      " [0 0 0 1 0 0 0 0]\n",
      " [0 0 1 0 0 0 0 0]\n",
      " [0 1 0 0 0 0 0 0]\n",
      " [1 0 0 0 0 0 0 0]]\n",
      "[[0 0 0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0 0 1]\n",
      " [0 0 0 0 0 0 1 0]\n",
      " [0 0 0 0 0 0 1 1]\n",
      " [0 0 0 0 1 1 1 1]\n",
      " [0 0 0 1 0 0 0 0]\n",
      " [0 0 1 0 0 0 0 0]\n",
      " [0 1 0 0 0 0 0 0]\n",
      " [1 0 0 0 0 0 0 0]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Warren Weckesser\n",
    "\n",
    "I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])\n",
    "B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)\n",
    "print(B[:,::-1])\n",
    "\n",
    "# Author: Daniel T. McDonald\n",
    "\n",
    "I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)\n",
    "print(np.unpackbits(I[:, np.newaxis], axis=1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 96. Given a two dimensional array, how to extract unique rows? (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 0 1]\n",
      " [0 1 0]\n",
      " [1 1 0]]\n",
      "[[0 0 1]\n",
      " [0 1 0]\n",
      " [1 1 0]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Jaime Fernández del Río\n",
    "\n",
    "Z = np.random.randint(0,2,(6,3))\n",
    "T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))\n",
    "_, idx = np.unique(T, return_index=True)\n",
    "uZ = Z[idx]\n",
    "print(uZ)\n",
    "\n",
    "# Author: Andreas Kouzelis\n",
    "# NumPy >= 1.13\n",
    "uZ = np.unique(Z, axis=0)\n",
    "print(uZ)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.06728041, 0.05397444, 0.0764441 , 0.22359054, 0.0836961 ,\n",
       "        0.23600838, 0.01241854, 0.22915715, 0.07803804, 0.18796029],\n",
       "       [0.17717534, 0.14213557, 0.20130688, 0.58880039, 0.22040419,\n",
       "        0.62150136, 0.03270283, 0.60345942, 0.20550435, 0.49497216],\n",
       "       [0.27189413, 0.21812194, 0.30892651, 0.90357594, 0.33823335,\n",
       "        0.95375901, 0.05018592, 0.92607176, 0.31536797, 0.75958668],\n",
       "       [0.06789412, 0.05446677, 0.07714139, 0.22563006, 0.08445954,\n",
       "        0.23816117, 0.01253182, 0.23124745, 0.07874988, 0.1896748 ],\n",
       "       [0.11831111, 0.09491285, 0.13442526, 0.39317904, 0.14717774,\n",
       "        0.41501553, 0.02183773, 0.40296779, 0.13722817, 0.33052403],\n",
       "       [0.23778707, 0.19076019, 0.27017402, 0.79022918, 0.29580454,\n",
       "        0.83411717, 0.04389047, 0.80990307, 0.27580745, 0.66430229],\n",
       "       [0.03397511, 0.02725589, 0.03860257, 0.11290827, 0.04226467,\n",
       "        0.119179  , 0.00627109, 0.11571928, 0.03940748, 0.09491578],\n",
       "       [0.08646755, 0.06936696, 0.09824455, 0.28735447, 0.10756469,\n",
       "        0.30331365, 0.01596008, 0.29450857, 0.10029306, 0.24156312],\n",
       "       [0.22622413, 0.18148404, 0.25703619, 0.75180248, 0.28142037,\n",
       "        0.79355631, 0.0417562 , 0.77051968, 0.26239568, 0.63199907],\n",
       "       [0.00686845, 0.00551008, 0.00780394, 0.02282566, 0.00854427,\n",
       "        0.02409336, 0.00126777, 0.02339393, 0.00796666, 0.01918828]])"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Author: Alex Riley\n",
    "# Make sure to read: http://ajcr.net/Basic-guide-to-einsum/\n",
    "\n",
    "A = np.random.uniform(0,1,10)\n",
    "B = np.random.uniform(0,1,10)\n",
    "\n",
    "np.einsum('i->', A)       # np.sum(A)\n",
    "np.einsum('i,i->i', A, B) # A * B\n",
    "np.einsum('i,i', A, B)    # np.inner(A, B)\n",
    "np.einsum('i,j->ij', A, B)    # np.outer(A, B)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Author: Bas Swinckels\n",
    "\n",
    "phi = np.arange(0, 10*np.pi, 0.1)\n",
    "a = 1\n",
    "x = a*phi*np.cos(phi)\n",
    "y = a*phi*np.sin(phi)\n",
    "\n",
    "dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths\n",
    "r = np.zeros_like(x)\n",
    "r[1:] = np.cumsum(dr)                # integrate path\n",
    "r_int = np.linspace(0, r.max(), 200) # regular spaced path\n",
    "x_int = np.interp(r_int, r, x)       # integrate path\n",
    "y_int = np.interp(r_int, r, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 99. Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n. (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[2. 0. 1. 1.]]\n"
     ]
    }
   ],
   "source": [
    "# Author: Evgeni Burovski\n",
    "\n",
    "X = np.asarray([[1.0, 0.0, 3.0, 8.0],\n",
    "                [2.0, 0.0, 1.0, 1.0],\n",
    "                [1.5, 2.5, 1.0, 0.0]])\n",
    "n = 4\n",
    "M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)\n",
    "M &= (X.sum(axis=-1) == n)\n",
    "print(X[M])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 100. Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means). (★★★)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-0.30976616  0.02882422]\n"
     ]
    }
   ],
   "source": [
    "# Author: Jessica B. Hamrick\n",
    "\n",
    "X = np.random.randn(100) # random 1D array\n",
    "N = 1000 # number of bootstrap samples\n",
    "idx = np.random.randint(0, X.size, (N, X.size))\n",
    "means = X[idx].mean(axis=1)\n",
    "confint = np.percentile(means, [2.5, 97.5])\n",
    "print(confint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "source": [],
    "metadata": {
     "collapsed": false
    }
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}